package com.liukaixin.product.ru.business.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.igexin.sdk.PushManager;
import com.liukaixin.product.ru.AppController;
import com.liukaixin.product.ru.R;
import com.liukaixin.product.ru.business.ViewPagerAdapter;
import com.liukaixin.product.ru.business.competition.competitionlist.CompetitionsFragment;
import com.liukaixin.product.ru.business.notice.NoticesActivity;
import com.liukaixin.product.ru.business.team.teamlist.TeamsFragment;
import com.liukaixin.product.ru.business.user.AboutUsActivity;
import com.liukaixin.product.ru.business.user.login.LoginActivity;
import com.liukaixin.product.ru.business.user.myapplies.MyAppliesActivity;
import com.liukaixin.product.ru.business.user.myfavorites.MyFavoritesActivity;
import com.liukaixin.product.ru.business.user.myteams.MyTeamsActivity;
import com.liukaixin.product.ru.business.user.userInfo.UserInfoActivity;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.service.PollingService;
import com.liukaixin.product.ru.util.CheckUtil;
import com.liukaixin.product.ru.util.PollingUtils;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.support.design.widget.TabLayout.MODE_FIXED;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.security.AccessController.getContext;

/**
 * Created by liukaixin on 16/8/28.
 */

public class HomeActivity extends AppCompatActivity
        implements View.OnClickListener {

    // 侧栏
    private DrawerLayout drawerLayout;
    // 标题栏
    private Toolbar toolbar;
    // tab栏
    private TabLayout tabLayout;
    // view pager
    private ViewPager viewPager;
    // 导航栏(侧栏)
    private NavigationView navigationView;
    private View headerLayout;
    private TextView navNameText;
    private CircleImageView profileImg;

    // TabLayout中的tab标题
    private String[] titles;
    // 填充到ViewPager中的Fragment
    private List<Fragment> fragments;

//    private MaterialSearchView searchView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        PushManager.getInstance().initialize(this.getApplicationContext());
        Logger.i("client id is %s", PushManager.getInstance()
                .getClientid(this.getApplicationContext()));
        // Start polling service
//        Logger.i("开始轮询");

//        PollingUtils.startPollingService(this, 10,
//                PollingService.class, PollingService.ACTION);

        // 初始化各种控件
        initViews();

        // 初始化mTitles、mFragments等ViewPager需要的数据
        initData();

        // 对各种控件进行设置、适配、填充数据
        configViews();
    }

    private void initViews() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_home);
        headerLayout.setOnClickListener(view -> {
            if (CheckUtil.isLogin() != null) {
                Intent toUserInfo = new Intent(HomeActivity.this, UserInfoActivity.class);
                startActivity(toUserInfo);
            } else {
                Intent toLogin = new Intent(HomeActivity.this, LoginActivity.class);
                startActivity(toLogin);
            }
        });
        navNameText = (TextView) headerLayout.findViewById(R.id.navi_name_text);
        profileImg = (CircleImageView) headerLayout.findViewById(R.id.profile_image);
    }

    @Override
    protected void onResume() {
        super.onResume();
        User user = CheckUtil.isLogin();
        if (user != null) {
            checkNotNull(user.getUsername());
            Glide.with(HomeActivity.this)
                    .load(user.getPic())
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(profileImg);
            navNameText.setText(user.getUsername());
            // 如果有新消息，显示通知

        } else {
            navNameText.setText("神秘人");
        }
    }

    private void initData() {
        titles = getResources().getStringArray(R.array.tab_titles);

        fragments = new ArrayList<>();
        CompetitionsFragment competitionsFragment = CompetitionsFragment.newInstance();
        fragments.add(competitionsFragment);

        TeamsFragment teamsFragment = TeamsFragment.newInstance();
        fragments.add(teamsFragment);
    }

    private void configViews() {
        // 设置显示Toolbar
        setSupportActionBar(toolbar);

        // 设置Drawerlayout开关指示器，即Toolbar最左边的那个icon
        ActionBarDrawerToggle actionBarDrawerToggle =
                new ActionBarDrawerToggle(this, drawerLayout, toolbar,
                        R.string.open, R.string.close);
        actionBarDrawerToggle.syncState();
        drawerLayout.addDrawerListener(actionBarDrawerToggle);

        // 自己写的方法，设置NavigationView中menu的item被选中后要执行的操作
        onNavigationViewMenuItemSelected(navigationView);

        // 初始化ViewPager的适配器，并设置给它
        ViewPagerAdapter viewPagerAdapter =
                new ViewPagerAdapter(getSupportFragmentManager(), titles, fragments);
        viewPager.setAdapter(viewPagerAdapter);
        // 设置ViewPager最大缓存的页面个数
        viewPager.setOffscreenPageLimit(1);

        tabLayout.setTabMode(MODE_FIXED);
        // 将TabLayout和ViewPager进行关联，让两者联动起来
        tabLayout.setupWithViewPager(viewPager);

//        searchView = (MaterialSearchView) findViewById(R.id.search_view);
//        searchView.setCursorDrawable(R.drawable.custom_cursor);
//        searchView.setVoiceSearch(false);
//        searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
//            @Override
//            public boolean onQueryTextSubmit(String query) {
//                //Do some magic
//                return false;
//            }
//
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                //Do some magic
//                return false;
//            }
//        });
//
//        searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
//            @Override
//            public void onSearchViewShown() {
//                //Do some magic
//            }
//
//            @Override
//            public void onSearchViewClosed() {
//                //Do some magic
//            }
//        });
    }

    /**
     * 设置NavigationView中menu的item被选中后要执行的操作
     *
     * @param navigationView
     */
    private void onNavigationViewMenuItemSelected(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(menuItem -> {

            switch (menuItem.getItemId()) {
//                case R.id.navigation_item_my_competition:
//                    toActivity(MyCompetitionsActivity.class);
//                    break;
                case R.id.navigation_item_logout:
                    AppController.getInstance().getCache().remove("user");
                    Toast.makeText(HomeActivity.this, "退出登录成功", Toast.LENGTH_SHORT).show();
                    navNameText.setText("神秘人");
                    profileImg.setImageResource(R.drawable.logo);
                    break;
                case R.id.navigation_item_my_team:
                    if (CheckUtil.isLogin() != null) {
                        Intent toMyTeam = new Intent(HomeActivity.this, MyTeamsActivity.class);
                        startActivity(toMyTeam);
                    } else {
                        toLogin();
                    }
                    break;
                case R.id.navigation_item_my_favorite:
                    if (CheckUtil.isLogin() != null) {
                        Intent toMyMyFavorite = new Intent(
                                HomeActivity.this, MyFavoritesActivity.class);
                        startActivity(toMyMyFavorite);
                    } else {
                        toLogin();
                    }
                    break;
                case R.id.navigation_item_about:
                    Intent toAboutUs = new Intent(
                            HomeActivity.this, AboutUsActivity.class);
                    startActivity(toAboutUs);
                    break;
                case R.id.navigation_item_my_apply:
                    if (CheckUtil.isLogin() != null) {
                        Intent toMyApplies = new Intent(HomeActivity.this, MyAppliesActivity.class);
                        startActivity(toMyApplies);
                    } else {
                        toLogin();
                    }
                    break;
                default:
                    break;
            }

            // Menu item点击后选中，并关闭Drawerlayout
            drawerLayout.closeDrawers();
            return true;
        });
    }

    private void toLogin() {
        Intent toLogin = new Intent(HomeActivity.this, LoginActivity.class);
        startActivity(toLogin);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_option_menu, menu);
//        MenuItem item = menu.findItem(R.id.action_search);
//        searchView.setMenuItem(item);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

//        if (id == R.id.action_search) {
//            searchView.setMenuItem(item);
//        } else if (id == R.id.action_notice) {
        if (CheckUtil.isLogin() != null) {
            Intent toNotice = new Intent(HomeActivity.this, NoticesActivity.class);
            startActivity(toNotice);
        } else {
            Intent toLogin = new Intent(HomeActivity.this, LoginActivity.class);
            startActivity(toLogin);
        }
//    }

        return true;
    }


    @Override
    public void onClick(View v) {
//        switch (v.getId()) {
        // FloatingActionButton的点击事件
//            case R.id.floating_button:
        // TODO: 16/9/3 delete after test
//                Intent toLogin = new Intent(this, LoginActivity.class);
//                startActivity(toLogin);
//                break;
////        }
    }

    @Override
    public void onBackPressed() {
//        if (searchView.isSearchOpen()) {
//            searchView.closeSearch();
//        } else {
        super.onBackPressed();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Stop polling service
        Logger.i("停止轮询");
        PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
    }
}
